package net.valerijtimakov.homefinances.dao.storages.common.mysql.query_builders;

import java.util.ArrayList;
import java.util.List;

import net.valerijtimakov.homefinances.exceptions.AppExceptionWrongState;

public class SelectQuery extends ConditionedQuery {
	
	private List<String> fieldsList = new ArrayList<String>();
	private String endCommands = "";
	private boolean selectAll = false;
	
	public SelectQuery() {
		super();
	}

	public SelectQuery(String tableName) {
		super(tableName);
	}

	public List<String> getFieldsList() {
		return fieldsList;
	}
	
	public void addField(String fieldName) {
		fieldsList.add(fieldName);
	}

	public String getEndCommands() {
		return endCommands;
	}

	public void setEndCommands(String endCommands) {
		this.endCommands = checkNull(endCommands);
	}
	
	public boolean isSelectAll() {
		return selectAll;
	}

	public void setSelectAll(boolean selectAll) {
		this.selectAll = selectAll;
	}

	@Override
	public String getSql() throws AppExceptionWrongState {
		if (tableName == null || tableName.isEmpty()) {
			throw new AppExceptionWrongState("Не задано имя таблицы!");
		}
		StringBuilder whereCondFull = where.getWhereConditionLine();
		if (whereCondFull.length() == 0 && !selectAll) {
			return "";
		}
		return "SELECT " + getFieldsLine() + " FROM `" +  tableName + "`" + 
			whereCondFull + endCommands + ";";
	}
	
	private StringBuilder getFieldsLine() {
		StringBuilder fieldsLine = new StringBuilder();
		if (fieldsList.size() == 0) {
			fieldsLine.append("*");
		} else {
			MySqlUtils.appendDBItemNames(fieldsLine, fieldsList);
		}
		return fieldsLine;
	}
}
